local ma__saogu = fk.CreateSkill{
  name = "ma__saogu",
  tags = { Skill.Switch },
}

Fk:loadTranslationTable{
  ["ma__saogu"] = "扫谷",
  [":ma__saogu"] = "转换技，出牌阶段/弃牌阶段结束时，你可以令你/一名其他角色：阳，弃置至少X张牌（若为此阶段已弃置过的花色则此阶段此技能失效），然后你可以使用其中的【杀】；"..
  "阴，摸X张牌（X为本回合此阶段被弃置过的花色数，至少为1）。",

  ["#ma__saogu-yang"] = "扫谷：弃置至少 %arg 张牌，令 %dest 使用其中的【杀】",
  ["#ma__saogu-yin"] = "扫谷：摸 %arg 张牌",
  ["@ma__saogu-phase"] = "扫谷",
  ["#ma__saogu-choose"] = "扫谷：你可以对其他角色发动“扫谷”",
  ["#ma__saogu-use"] = "扫谷：你可以使用其中的【杀】",

  ["$ma__saogu1"] = "铁骑如巨浪，势起可摧祁连、踏龙庭。",
  ["$ma__saogu2"] = "我有青霜剑一柄，欲斩天下不寒秋。",
}

local U = require "packages/utility/utility"

local function Doma__saogu(player, ids)
  local room = player.room
  ids = table.filter(ids, function (id)
    return table.contains(room.discard_pile, id) and Fk:getCardById(id).trueName == "slash"
  end)
  while not player.dead do
    ids = table.filter(ids, function (id)
      return table.contains(room.discard_pile, id)
    end)
    if #ids == 0 then return end
    local use = room:askToUseRealCard(player, {
      pattern = ids,
      skill_name = ma__saogu.name,
      prompt = "#ma__saogu-use",
      extra_data = {
        bypass_distances = true,
        bypass_times = true,
        extraUse = true,
        expand_pile = ids,
      },
      skip = true,
    })
    if use then
      table.removeOne(ids, use.card:getEffectiveId())
      room:useCard(use)
    else
      break
    end
  end
end

ma__saogu:addEffect("active", {
  anim_type = "switch",
  min_card_num = function(self, player)
    if player:getSwitchSkillState(ma__saogu.name, false) == fk.SwitchYang then
      return math.max(1, #player:getTableMark("@ma__saogu-phase"))
    else
      return 0
    end
  end,
  target_num = 0,
  prompt = function(self, player)
    if player:getSwitchSkillState(ma__saogu.name, false) == fk.SwitchYang then
      return "#ma__saogu-yang::"..player.id..":"..math.max(1, #player:getTableMark("@ma__saogu-phase"))
    else
      return "#ma__saogu-yin:::"..math.max(1, #player:getTableMark("@ma__saogu-phase"))
    end
  end,
  can_use = Util.TrueFunc,
  card_filter = function(self, player, to_select, selected)
    return player:getSwitchSkillState(ma__saogu.name, false) == fk.SwitchYang and not player:prohibitDiscard(to_select)
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    if player:getSwitchSkillState(ma__saogu.name, true) == fk.SwitchYang then
      local invalid = table.find(effect.cards, function(id)
        return table.contains(player:getTableMark("@ma__saogu-phase"), Fk:getCardById(id):getSuitString(true))
      end)
      room:throwCard(effect.cards, ma__saogu.name, player, player)
      Doma__saogu(player, effect.cards)
      if invalid then
        room:invalidateSkill(player, ma__saogu.name, "-phase")
      end
    else
      player:drawCards(math.max(1, #player:getTableMark("@ma__saogu-phase")), ma__saogu.name)
    end
  end,
})
ma__saogu:addEffect(fk.EventPhaseEnd, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(ma__saogu.name) and player.phase == Player.Discard
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    if player:getSwitchSkillState(ma__saogu.name, true) == fk.SwitchYang then
      targets = table.filter(room:getOtherPlayers(player, false), function(p)
        return not p:isNude()
      end)
    else
      targets = room:getOtherPlayers(player, false)
    end
    local to = room:askToChoosePlayers(player, {
      min_num = 1,
      max_num = 1,
      targets = targets,
      skill_name = ma__saogu.name,
      prompt = "#ma__saogu-choose",
      cancelable = true,
    })
    if #to > 0 then
      event:setCostData(self, {tos = to})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    if not to.dead then
      if player:getSwitchSkillState(ma__saogu.name, true) == fk.SwitchYang then
        local n = math.max(1, #player:getTableMark("@ma__saogu-phase"))
        local cards
        if #to:getCardIds("he") <= n then
          cards = to:getCardIds("he")
          room:throwCard(cards, "ma__saogu", to, to)
        else cards = room:askToDiscard(to, {
          min_num = n,
          max_num = 999,
          include_equip = true,
          skill_name = ma__saogu.name,
          cancelable = false,
          prompt = "#ma__saogu-yang:"..math.max(1, #player:getTableMark("@ma__saogu-phase")).."::"..player.id,
        })
        end
        if #cards > 0 then
          local invalid = table.find(cards, function(id)
            return table.contains(player:getTableMark("@ma__saogu-phase"), Fk:getCardById(id):getSuitString(true))
          end)
          Doma__saogu(player, cards)
          if invalid then
            room:invalidateSkill(player, ma__saogu.name, "-phase")
          end
        end
      else
        to:drawCards(math.max(1, #player:getTableMark("@ma__saogu-phase")), ma__saogu.name)
      end
    end
  end,
})

ma__saogu:addEffect(fk.AfterCardsMove, {
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(ma__saogu.name) and
      (player.phase == Player.Play or player.phase == Player.Discard)
  end,
  on_refresh = function (self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.moveReason == fk.ReasonDiscard then
        for _, info in ipairs(move.moveInfo) do
          local suit = Fk:getCardById(info.cardId):getSuitString(true)
          if suit ~= "log_nosuit" then
            player.room:addTableMarkIfNeed(player, "@ma__saogu-phase", suit)
          end
        end
      end
    end
  end,
})

ma__saogu:addAcquireEffect(function (self, player, is_start)
  if player.phase == Player.Play or player.phase == Player.Discard then
    local room = player.room
    room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
      for _, move in ipairs(e.data) do
        if move.moveReason == fk.ReasonDiscard then
          for _, info in ipairs(move.moveInfo) do
            local suit = Fk:getCardById(info.cardId):getSuitString(true)
            if suit ~= "log_nosuit" then
              player.room:addTableMarkIfNeed(player, "@ma__saogu-phase", suit)
            end
          end
        end
      end
    end, Player.HistoryPhase)
  end
end)

return ma__saogu
